import React, { useEffect, useState } from 'react';
import {
  View, StyleSheet, FlatList, RefreshControl
} from 'react-native';

import { TaskItem } from '../../components';
import Http from '../../service/http';
import requestCheck from '../../utils/RequestCheckUtil';
import { colors } from '../../constants/theme';


export default function TaskListScreen({ type, navigation }) {
  const { state: { params: { instanceId } } } = navigation;
  const [ecnType, setEcnType] = useState(null);
  const [dataSource, setDataSource] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [refresh, setRefresh] = useState(0);

  useEffect(() => {
    const didFocusListener = navigation.addListener(
      'didFocus',
      () => { setRefresh(refresh + 1); },
    );
    return () => didFocusListener.remove();
  }, [navigation, refresh, setRefresh, type]);

  useEffect(() => {
    async function fetchData() {
      const res = await Http.getTaskList({ instanceId });
      const callback = ({ type: t, tasks }) => {
        setEcnType(t);
        setDataSource(tasks[type] || []);
      };
      requestCheck(res, callback, navigation);
      setIsLoading(false);
    }
    fetchData();
  }, [instanceId, navigation, type, refresh]);

  return (
    <View style={styles.container}>
      <FlatList
        style={{ flex: 1 }}
        data={dataSource}
        renderItem={({ item }) => (
          <TaskItem
            item={item}
            ecnType={ecnType}
            type={type}
            instanceId={instanceId}
            refresh={refresh}
            setRefresh={setRefresh}
          />
        )}
        keyExtractor={({ taskId }) => taskId}
        refreshControl={(
          <RefreshControl
            title="加载中"
            titleColor={colors.secondary}
            colors={[colors.primary, colors.secondary]}
            tintColor={colors.primary}
            refreshing={isLoading}
            onRefresh={() => setRefresh(refresh + 1)}
          />
        )}
      />
    </View>
  );
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  taskItem: {
    borderWidth: 2,
    borderColor: 'black'

  }
});
